<?php

mysqli_connect ( 'localhost', 'root', 'fred' );

function do_export()
{
	global $DB, $VERSION;
	$rt = $_REQUEST[ 't' ];
	$t = split ( ",", $rt );
	$th = array_flip ( $t );
	$ct = count ( $t );
	$z = db_array ( "show variables like 'max_allowed_packet'" );
	$MAXI = floor ( $z[ 0 ][ 'Value' ] * 0.8 );
	if ( ! $MAXI ) $MAXI = 838860;
	
	if ( $ct == 1 && $_REQUEST[ 'et' ] == 'csv' )
	{
		header ( 'Content-type: text/csv' );
		header ( "Content-Disposition: attachment; filename=\"$t[0].csv\"" );
		
		$csv_data = "First Name,Last Name,Email,ClickBank ID,Registered\n";
		$sth = db_query ( "select * from `$t[0]`" );
		$fn = mysql_num_fields ( $sth );
		for( $i = 0; $i < $fn; $i ++ )
		{
			$m = mysql_fetch_field ( $sth, $i );
			echo qstr ( $m->name ) . ( ( $i < $fn - 1 ) ? "," : "" );
		}
		echo "\n";
		while ( $row = mysql_fetch_row ( $sth ) )
		{
			echo to_csv_row ( $row );
		}
		exit ();
	}
	
	header ( 'Content-type: text/plain' );
	header ( "Content-Disposition: attachment; filename=\"$DB[db]" . ( ( $ct == 1 && $t[ 0 ] ) ? ".$t[0]" : ( ( $ct > 1 ) ? '.' . $ct . 'tables' : '' ) ) . ".sql\"" );
	echo "-- phpMiniAdmin dump $VERSION\n-- Datetime: " . date ( 'Y-m-d H:i:s' ) . "\n-- Host: $DB[host]\n-- Database: $DB[db]\n\n/*!40030 SET max_allowed_packet=$MAXI */;\n\n";
	
	$sth = db_query ( "show tables from $DB[db]" );
	while ( $row = mysql_fetch_row ( $sth ) )
	{
		if ( ! $rt || array_key_exists ( $row[ 0 ], $th ) ) do_export_table ( $row[ 0 ], 1, $MAXI );
	}
	
	echo "\n-- phpMiniAdmin dump end\n";
	exit ();
}

function do_export_table( $database = '', $table = '', $type = 'sql' )
{
	if ( $type == 'csv' )
	{
		$tables = mysqli_query ( "SHOW CREATE TABLE `$table`" );
		$row = mysqli_fetch_row ( $tables );
		
		echo "DROP TABLE IF EXISTS `$table`; \n $row[1]; \n\n";
	}
	
	if ( $type == 'sql' )
	{
		$exsql = '';
		echo "/*!40000 ALTER TABLE `$table` DISABLE KEYS */;\n";
		
		$sth = db_query ( "SELECT * FROM `$table`" );
		
		while ( $row = mysqli_fetch_row ( $sth ) )
		{
			$values = '';
			
			foreach ( $row as $v )
				$values .= ( ( $values ) ? ',' : '' ) . dbq ( $v );
			$exsql .= ( ( $exsql ) ? ',' : '' ) . "(" . $values . ")";
			
			if ( strlen ( $exsql ) > $MAXI )
			{
				echo "INSERT INTO `$table` VALUES $exsql;\n";
				
				$exsql = '';
			}
		}
		
		if ( $exsql ) echo "INSERT INTO `$table` VALUES $exsql;\n";
		echo "/*!40000 ALTER TABLE `$table` ENABLE KEYS */;\n";
		echo "\n";
	}
	flush ();
}

?>